package com.hnchances.security;

import com.hnchances.pojo.entity.User;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
public class LoginUserDetails implements UserDetails {

    //角色名称列表，用于授权
    private List<String> roleNames;
    //权限名称列表，用户授权
    private List<String> permissionNames;

    private User user;

    public LoginUserDetails(User user, List<String> roleNames, List<String> permissionNames){
        this.user = user;
        this.roleNames = roleNames;
        this.permissionNames = permissionNames;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 添加角色
        if (!CollectionUtils.isEmpty(roleNames) ){
            // 将角色设置到GrantedAuthority中，官网要求角色要加上前缀 ROLE_xxx 区分其它权限
            for (String roleName : roleNames) {
                authorities.add(new SimpleGrantedAuthority("ROLE_"+roleName));
            }
        }
        // 添加权限
        if (!CollectionUtils.isEmpty(permissionNames)){
            for (String permissionName : permissionNames) {
                authorities.add(new SimpleGrantedAuthority(permissionName));
            }
        }
        return List.of();
    }

    @Override
    public String getPassword() {
        return this.user.getPassword();
    }

    @Override
    public String getUsername() {
        return this.user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
